package felix.rule.module.delay;

import felix.rule.api.*;
import felix.rule.api.util.TNodeUtils;
import felix.rule.data.msg.EngineMsg;
import felix.rule.data.msg.EngineMsgMetaData;
import felix.rule.data.plugin.ComponentType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RuleNode(
        type = ComponentType.ACTION,
        name = "delay",
        configClazz = TMsgDelayNodeConfiguration.class,
        nodeDescription = "Delays incoming message",
        nodeDetails = "Delays messages for configurable period. Please note, this node acknowledges the message from the current queue (message will be removed from queue)",
        icon = "pause",
        uiResources = {"static/rulenode/rulenode-core-config.js"},
        configDirective = "tActionNodeMsgDelayConfig"
)

public class TMsgDelayNode implements TNode {

    private static final String TB_MSG_DELAY_NODE_MSG = "TMsgDelayNodeMsg";

    private TMsgDelayNodeConfiguration config;
    private Map<UUID, EngineMsg> pendingMsgs;

    @Override
    public void init(TContext ctx, TNodeConfiguration configuration) throws TNodeException {
        this.config = TNodeUtils.convert(configuration, TMsgDelayNodeConfiguration.class);
        this.pendingMsgs = new HashMap<>();
    }

    @Override
    public void onMsg(TContext ctx, EngineMsg msg) {
        if (msg.getType().equals(TB_MSG_DELAY_NODE_MSG)) {
            EngineMsg pendingMsg = pendingMsgs.remove(UUID.fromString(msg.getData()));
            if (pendingMsg != null) {
                ctx.tellSuccess(pendingMsg);
            }
        } else {
            if (pendingMsgs.size() < config.getMaxPendingMsgs()) {
                pendingMsgs.put(msg.getId(), msg);
                EngineMsg tickMsg = ctx.newMsg("MAIN", TB_MSG_DELAY_NODE_MSG, ctx.getSelfId(), new EngineMsgMetaData(), msg.getId().toString());
                ctx.tellSelf(tickMsg, getDelay(msg));
            } else {
                ctx.tellFailure(msg, new RuntimeException("Max limit of pending messages reached!"));
            }
        }
    }

    private long getDelay(EngineMsg msg) {
        int periodInSeconds;
        if (config.isUseMetadataPeriodInSecondsPatterns()) {
            if (isParsable(msg, config.getPeriodInSecondsPattern())) {
                periodInSeconds = Integer.parseInt(TNodeUtils.processPattern(config.getPeriodInSecondsPattern(), msg.getMetaData()));
            } else {
                throw new RuntimeException("Can't parse period in seconds from metadata using pattern: " + config.getPeriodInSecondsPattern());
            }
        } else {
            periodInSeconds = config.getPeriodInSeconds();
        }
        return TimeUnit.SECONDS.toMillis(periodInSeconds);
    }

    private boolean isParsable(EngineMsg msg, String pattern) {
        return NumberUtils.isParsable(TNodeUtils.processPattern(pattern, msg.getMetaData()));
    }

    @Override
    public void destroy() {
        pendingMsgs.clear();
    }
}
